﻿using System;
using System.Collections.Generic;
using System.Text;
using 立库托盘入库.bean;
using 立库托盘入库.MyInterface;
using System.IO.Ports;
using System.Threading;
using System.Windows;
using System.IO;
using System.Xml.Linq;
using System.Diagnostics;

namespace 立库托盘入库.Until
{
    class ComUntil
    {

        /// PLC地址
        public string PLC_add = "10";


        SerialPort ScanSerialPort;
        /**扫描枪串口名*/
        ChuanKouBean COM_Scrn = new ChuanKouBean();


        MainInterface M;

        /**扫描串口连接状态*/
        Boolean ischuankou = false;
        /**初始化类*/
        public ComUntil(MainInterface mainInterface)
        {
            this.M = mainInterface;
        }

        /**初始化串口*/
        public void InitCOM()
        {
            String[] chuankous = SerialPort.GetPortNames();
            Console.WriteLine(chuankous.Length);
            if (chuankous.Length > 0)
            {
                ScanSerialPort = new SerialPort(COM_Scrn.PortName, COM_Scrn.BaudRate, getparity(COM_Scrn.Parity), COM_Scrn.DataBits, getstopBits(COM_Scrn.StopBits));
                ScanSerialPort.ReceivedBytesThreshold = 1;
                ScanSerialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_pan1_DataReceived);
                ischuankou = OpenPort(ScanSerialPort);//串口打开
                
            }
            else
            {
                MessageBox.Show("未检测到有连接的扫描枪，无法扫描");
            }

        }
                                  

        /**获取设置的串口和刷新串口*/
        public void readCOMs(Boolean ischongqi,String path)
        {
            
            try
            {
                if (Directory.Exists(path + "save") == false)//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(path + "save");
                }
                if (File.Exists(path + "save\\ChuanKou.xml"))
                {
                    string filePath = path + "save\\ChuanKou.xml";
                    XElement xmlDoc = XElement.Load(filePath);
                    //XElement d = xmlDoc.Element("UserData");
                    var data = xmlDoc.Descendants("ChuanKouBean");
                    foreach (var item in data)
                    {
                        COM_Scrn.PortName = item.Element("PortName").Value;
                        COM_Scrn.BaudRate = int.Parse(item.Element("BaudRate").Value);
                        COM_Scrn.Parity = item.Element("Parity").Value;
                        COM_Scrn.DataBits = int.Parse(item.Element("DataBits").Value);
                        COM_Scrn.StopBits = item.Element("StopBits").Value;
                    }
                }
                else
                {
                    //不存在文件
                    //Directory.CreateDirectory(path + "save\\Login.xml");//创建该文件

                    string filePathOne = System.IO.Path.Combine(path + "save", "ChuanKou.xml");
                    File.Create(filePathOne);
                }

                if (ischongqi)
                {
                    if (ScanSerialPort != null)
                    {
                        ischuankou = false;
                        ScanSerialPort.Close();
                    }
                    InitCOM();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("sssssssssssss" + e.ToString());
            }


           
        }

        /**打开串口的方法*/
        public bool OpenPort(SerialPort serialPort)
        {
            try//这里写成异常处理的形式以免串口打不开程序崩溃
            {
                serialPort.Open();
            }
            catch { }
            if (serialPort.IsOpen)
            {

                MessageBox.Show("串口打开成功!");
                return true;
            }
            else
            {
                MessageBox.Show("串口打开失败!");
                return false;
            }
        }

        /**扫描枪扫描到后返回*/
        private void serialPort_pan1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Debug.WriteLine("=========================");
            Thread.Sleep(200);
            var s = ScanSerialPort.ReadExisting();
            M.scrm_com(s);
        }

        /**获取校验位*/
        public Parity getparity(String parity)
        {
            if (parity == "NONE")
            {
                return Parity.None;
            }
            if (parity == "ODD")
            {
                return Parity.Odd;
            }
            if (parity == "EVEN")
            {
                return Parity.Even;
            }
            return Parity.None;
        }

        /**获取停止位*/
        public StopBits getstopBits(String stopBits)
        {
            if (stopBits == "NONE")
            {
                return StopBits.None;
            }
            if (stopBits == "ONE")
            {
                return StopBits.One;
            }
            if (stopBits == "TWO")
            {
                return StopBits.Two;
            }
            return StopBits.None;
        }
    }
}

